from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_cors import CORS  # 新增
import os
from marshmallow import fields

app = Flask(__name__)
CORS(app)  # 启用CORS

# 数据库配置（请确保密码、数据库名正确）
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://202201020139:%40hnucm1254@106.53.194.250:63306/202201020139'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
ma = Marshmallow(app)

# 定义数据模型
class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    age = db.Column(db.Integer)
    gender = db.Column(db.String(10))
    phone = db.Column(db.String(20))

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'age': self.age,
            'gender': self.gender,
            'phone': self.phone
        }

class PersonSchema(ma.Schema):
    id = fields.Integer(dump_only=True)
    name = fields.String(required=True)
    age = fields.Integer()
    gender = fields.String()
    phone = fields.String()

person_schema = PersonSchema()
persons_schema = PersonSchema(many=True)

with app.app_context():
    db.create_all()

@app.route('/api/persons', methods=['GET'])
def get_persons():
    page = request.args.get('page', 1, type=int)
    search = request.args.get('search', '')
    query = Person.query
    if search:
        query = query.filter(Person.name.ilike(f'%{search}%'))
    persons = query.paginate(page=page, per_page=10, error_out=False).items
    return jsonify(persons_schema.dump(persons))

# 其他路由（POST/PUT/DELETE）保持不变...
# 添加人员信息
@app.route('/api/persons', methods=['POST'])
def add_person():
    data = request.get_json()
    new_person = Person(
        name=data['name'],
        age=data['age'],
        gender=data['gender'],
        phone=data['phone']
    )
    db.session.add(new_person)
    db.session.commit()
    return jsonify(new_person.to_dict()), 201

# 获取单个人员
@app.route('/api/persons/<id>', methods=['GET'])
def get_person(id):
    person = Person.query.get(id)
    return person_schema.jsonify(person)

# 更新人员
@app.route('/api/persons/<id>', methods=['PUT'])
def update_person(id):
    person = Person.query.get(id)

    name = request.json['name']
    age = request.json['age']
    gender = request.json['gender']
    phone = request.json['phone']

    person.name = name
    person.age = age
    person.gender = gender
    person.phone = phone

    db.session.commit()

    return person_schema.jsonify(person)

# 删除人员
@app.route('/api/persons/<id>', methods=['DELETE'])
def delete_person(id):
    person = Person.query.get(id)
    db.session.delete(person)
    db.session.commit()

    return person_schema.jsonify(person)


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000)  # 确保端口与前端一致